import { queryStoreBasics } from '@/services/coupon.service';
import { useDeepCompareEffect } from 'ahooks';
import { Col, message, Row, Space, Tag } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import DebounceSelect from '../DebounceSelect';
import styles from './index.less';

type TProps = {
  title: string;
  onChange: TAnyFunction;
  data: any[];
  type: any;
  stepThreeRef?: any;
};

const Search: FC<TProps> = (props) => {
  const { title, data, onChange, type, stepThreeRef } = props;
  const [showValue, setShowValue] = useState<any[]>([]);
  console.log('key', title);

  const handleChange = (newValue: TLabelValueData[]) => {
    onChange &&
      onChange(
        newValue.map((obj) => ({
          code: obj.value,
          name: obj.label,
        })),
      );
  };

  const handleTagClose = (id: string | number) => {
    const retValue = [...showValue];
    const index = retValue.findIndex((o) => o.value === id);
    retValue.splice(index, 1);
    onChange &&
      onChange(
        retValue.map((obj) => ({
          code: obj.value,
          name: obj.label,
        })),
      );
  };

  const fetchData = async (val: any): Promise<TIdNameData[]> => {
    const { storeRange } = stepThreeRef?.current?.getFieldsValue(['storeRange']) || {};

    const params = {
      name: val,
      type: 1,
      storeRange: '',
    };
    console.log('key1', type, title);
    if (type === 'market') {
      params.type = 1;
    } else if (type === 'city') {
      params.type = 2;
    } else if (type === 'district') {
      params.type = 3;
    } else if (type === 'store') {
      params.type = 4;
      params.storeRange = storeRange;
    }
    const { code, data: datas = [], message: msg } = await queryStoreBasics(params);
    if (code === 0) {
      const list: any = [];
      datas.map((item: any) => {
        // list.push({
        //   id: item.code,
        //   name: item.name,
        // });
        list.push(item);
      });
      return list;
    } else {
      message.error(msg);
      return [];
    }
    // return new Promise((res) => {
    //   setTimeout(() => {
    //     res([
    //       {
    //         id: 1,
    //         name: '牛肉(18个)',
    //       },
    //       {
    //         id: 2,
    //         name: '鸡肉(24个)',
    //       },
    //       {
    //         id: 3,
    //         name: '猪肉(36个)',
    //       },
    //     ]);
    //   }, 1000);
    // });
  };

  useDeepCompareEffect(() => {
    if (data) {
      setShowValue(
        data.map((o) => ({
          label: o.name,
          value: o.code,
          goodsNames: o.goodsNames || [],
        })),
      );
    }
  }, [data]);

  return (
    <div className={styles.choseContainer} style={{ border: 'none' }}>
      <Row>
        <Col span={24}>
          <DebounceSelect
            mode="multiple"
            value={showValue}
            fieldNames={{
              label: 'name',
              value: 'code',
            }}
            maxTagCount="responsive"
            placeholder={`请输入${title}`}
            fetchOptions={fetchData as any}
            onChange={handleChange as any}
            style={{ width: '300px' }}
          />
        </Col>

        <Col span={24} className="mt-16">
          <Space wrap>
            {showValue.map((o) => (
              <Tag
                key={o.value}
                closable
                onClose={() => {
                  handleTagClose(o.value);
                }}
              >
                {o.label}
              </Tag>
            ))}
          </Space>
        </Col>
      </Row>
    </div>
  );
};

export default Search;
